<template>
	<div>
		<el-dialog v-model="dialogVisible" title="选择人员" width="700px">
			<el-form inline>
				<el-form-item label="用户名称">
					<el-input v-model="form.username" placeholder="请输入用户名称"></el-input>
				</el-form-item>
				<el-form-item label="真实姓名">
					<el-input v-model="form.realName" placeholder="请输入真实姓名"></el-input>
				</el-form-item>
				<el-form-item label="手机号码">
					<el-input v-model="form.phone" placeholder="请输入手机号码"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button icon="Search" type="primary" @click="getTableData">搜索</el-button>
					<el-button icon="Refresh" @click="resetForm">重置</el-button>
				</el-form-item>
			</el-form>
			<el-table :data="tableData" border stripe ref="UserTable">
				<el-table-column type="selection"></el-table-column>
				<el-table-column label="用户姓名" prop="username"></el-table-column>
				<el-table-column label="真实姓名" prop="realName"></el-table-column>
				<el-table-column label="手机号" prop="phone"></el-table-column>
			</el-table>
			<XlxPagination v-model:currentPage="form.current" v-model:pageSize="form.size" :total="totals"
				@update:currentPage="getTableData" @update:pageSize="updateSize">
			</XlxPagination>
			<template #footer>
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit">确认</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { getUserPageApi } from '@renderer/api/user';
import { IUsersList, Record } from '@renderer/interface/user';
import { ref, watch } from 'vue';

// 自定义事件
const emits = defineEmits(['addSuccess'])
// 接收父组件的 v-model
const dialogVisible = defineModel({ default: false })

/* 表单数据 */
const formValue = (): IUsersList => ({
	current: 1,
	size: 5,
	username: '',
	realName: '',
	phone: ''
})
const form = ref<IUsersList>(formValue())
// 重置表单
const resetForm = () => {
	form.value = formValue()
	getTableData()
}

/* 表格数据 */
const tableData = ref<Record[]>([])

// 获取表格数据
const getTableData = async () => {
	const { code, data } = await getUserPageApi(form.value)
	if (code !== '200') return

	tableData.value = data.records
	totals.value = data.total
}

/* 分页器数据 */
const totals = ref(0)
const updateSize = () => {
	form.value.current = 1
	getTableData()
}


/* 确认按钮 */
const UserTable = ref()
const selctedUser = ref<{ id: string, username: string }>({
	id: '',
	username: ''
})
// 提交数据
const postRoleData = async () => {
	dialogVisible.value = false

	// 通知父组件
	emits('addSuccess', selctedUser.value)
}
// 点击确认按钮
const onSubmit = () => {
	// 把选中的项的realName存起来
	selctedUser.value.id = UserTable.value.getSelectionRows()[0].id
	selctedUser.value.username = UserTable.value.getSelectionRows()[0].username

	postRoleData()
}

watch(dialogVisible, () => {
	if (dialogVisible.value) {
		// 打开 dialog 时获取数据
		getTableData()
	} else {
		// 关闭 dialog 时清空数据
		form.value = formValue()
	}
})
</script>

<style scoped lang="scss"></style>